# Program info
# LIBRARY is the library filename "$(LIBRARY).so"
# LUANAME is the Lua table name
# OS and ARCH are currently only used as defines for the preprocessor.
LIBRARY = blob
LUANAME = Blob
OS = LINUX
ARCH = x86

# The C preprocessor is a massive pile of ass
STUPIDFUNCNAMEHACK = luaopen_$(LIBRARY)

# Library installation path
#INSTALLPATH=/usr/lib/lua/5.1/
INSTALLPATH=/usr/local/lib/lua/5.1/
#INSTALLPATH=/home/hyperhacker/dev/lua/libs

# Options to pass to linker
LDOPTIONS =

# Other files that must be present to compile.
OTHER_DEP =

# Path to library files.
LIBPATH = /usr/lib/

# Libraries being used.
#LIBS = -L$(LIBPATH) -llua -lm `pkg-config --libs gtk+-2.0`
LIBS = -L$(LIBPATH)

# Additional directories for header files.
INCLUDES = -I$(SHARED) -I$(LUA)

# Used to generate build ID. Change BUILD_INDEX if multiple releases in one day.
DAY = `date +%-d`
MONTH = `date +%-m`
YEAR = `date +%-y`
BUILD_INDEX = 0
BUILD_ID = "((BUILD_YEAR << 13) | (BUILD_MONTH << 9) | (BUILD_DAY << 4) | BUILD_INDEX)"
BUILD_DEFS = -DBUILD_DAY=$(DAY) -DBUILD_MONTH=$(MONTH) -DBUILD_YEAR=$(YEAR) -DBUILD_INDEX=$(BUILD_INDEX) -DBUILD_ID=$(BUILD_ID)

# Variables to define for the preprocessor.
DEFS = -DPROGRAMNAME="\"$(PROGNAME)\"" -D$(OS) -DOSNAME=\"$(OS)\" -DARCH=$(ARCH) -DLUANAME=\"$(LUANAME)\" -DLUAOPENFUNC=$(STUPIDFUNCNAMEHACK) $(BUILD_DEFS)

# Commands and flags used for various actions
LUA_CFLAGS = `pkg-config lua5.1 --cflags`
DELETE = rm -rf
CXX = gcc
CXXFLAGS = -O3 -Wall $(DEFS) -fpic -c -o $(INCLUDES) $(LIBS)
LD = $(CXX)
LDFLAGS = -O2 -fpic $(LIBS) -c -o $(LIBRARY).o $(LIBRARY).c
COMPILE = $(CXX) $(CXXFLAGS) -c
MAKESO = $(CXX) -O $(LIBS) -shared -fpic -o

# Make library
all: $(LIBRARY).so

# Install
install:
	cp $(LIBRARY).so $(INSTALLPATH)
	
.PHONY : all install clean

$(LIBRARY): $(OBJS)
	@echo LD
	$(LD) $(LDFLAGS) $(OBJS) $(LIBS) $(LDOPTIONS)
	
%.o: %.c $(OTHER_DEP)
	@echo COMPILE
	$(COMPILE) $(<) -o $(@)

$(LIBRARY).so: $(SHARED_OBJS) $(LIBRARY).o
	@echo MAKESO
	$(MAKESO) $(@) $(^)
	
$(SHARED_OBJS): $(SHARED_SRCS)
	@echo COMPILE SHARED
	$(COMPILE) $(^)
	
#this is stupidly complex for a simple recursive delete V_v
clean:
	$(DELETE) $(LIBRARY)
	find . -name "*.la" -exec rm -f {} \;
	find . -name "*.lo" -exec rm -f {} \;
	find . -name "*.so" -exec rm -f {} \;
	find . -name "*.o" -exec rm -f {} \;
	find . -name "*.log" -exec rm -f {} \;
